package com.haidechizi.designpattern.proxy.dynamic.javasis;

import javassist.util.proxy.MethodFilter;
import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.Proxy;
import javassist.util.proxy.ProxyFactory;

import java.lang.reflect.Method;

/**
 * @author haidechizi
 */
public class JavassistProxyFactory {

    public static <T> T getProxy(Class<T> clazz) throws IllegalAccessException, InstantiationException {
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setSuperclass(clazz);
        proxyFactory.setFilter(new MethodFilter() {
            @Override
            public boolean isHandled(Method m) {
                // ignore finalize()
                return !m.getName().equals("finalize");
            }
        });

        Class<?> c = proxyFactory.createClass();
        MethodHandler mi = new MethodHandler() {
            @Override
            public Object invoke(Object self, Method m, Method proceed,
                                 Object[] args) throws Throwable {
                System.out.println("开始执行方法");
//                System.out.println("method name: " + m.getName() + " exec");
                Object result = proceed.invoke(self, args);  // execute the original method.
                System.out.println("执行方法结束");
                return result;
            }
        };
        Object proxy = c.newInstance();
        ((Proxy) proxy).setHandler(mi);
        return (T) proxy;
    }
}
